#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2007 Google Inc.
#
#
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import mail
import cgi
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import urlfetch
import urllib # Used to unescape URL parameters.
#import settings

try:
  from xml.etree import ElementTree
except ImportError:
  from elementtree import ElementTree
import gdata.calendar.service#Google data calender
import gdata.service
import atom.service
import gdata.calendar
import atom
import getopt
import sys
import string
import time
import datetime
from google.appengine.api import urlfetch
#import ssl

def sendsms2me(t,m):
    e={}
    e['m']=m
    e['t']=t
    em= urllib.urlencode(e)    
    xmail='http://palm2you.appspot.com/xmail'  
    
    req=urlfetch.fetch(xmail,payload=em,method=urlfetch.POST,headers={},allow_truncated=False,follow_redirects=False)
#    content=str(req.content.decode("utf8"))
class Xappletouch(webapp.RequestHandler):
    def __init__(self):
        self.applehead='http://store.apple.com/'
    def get(self):
        country=self.request.get('c')
        self.curtime=str(datetime.datetime.now())
        
#        print('start at:',datetime.datetime.now())
    #    sendsms2me('start at:'+str(datetime.now()))
    #    while 1:
#        self.hktouch()
#        self.cntouch()
#        self.hkipadcheck()
        self.ipadcheck(country)
    def ipadcheck(self,country):
        url=self.applehead+country+'/browse/home/shop_ipad/family/ipad/select?mco=MjE2MjYyNzA'
        req=urlfetch.fetch(url,method=urlfetch.GET,headers={},allow_truncated=False,follow_redirects=False)
        content=req.content
        tag='16 GB'
        tag2='32 GB'
        p1=content.find(tag)
        p2=content.find(tag2,p1)
        s=content[p1:p2]
        if s.find('form')>0:
            self.response.out.write(self.curtime+'--'+country+'-- has ipad2 now<br>')
            sendsms2me(country+'--'+self.curtime,country+' has ipad2 now')
        else:
            self.response.out.write(self.curtime+'--'+country+'-- has not ipad2<br>')            
   
           
def main():
    application = webapp.WSGIApplication([('/apple',Xappletouch)],
                                         debug=True)
    util.run_wsgi_app(application)=


if __name__ == '__main__':
    main()